package mylab.starters.mybatis.support.dynamicTable;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import lombok.extern.slf4j.Slf4j;
import mylab.starters.mybatis.config.dynamicTable.DynamicTableProperties;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年10月15日 11:02 上午
 */
@Slf4j
public class DefaultTableNameHandler implements TableNameHandler {

    DynamicTableProperties properties;

    public DefaultTableNameHandler(DynamicTableProperties properties) {
        this.properties = properties;
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (properties != null && properties.getTables() != null) {
            TableNameHandler handler = properties.getHandlerByTable(tableName);
            if (handler != null) {
                if (handler instanceof AutoCreatedTableNameHandler) {
                    AutoCreatedTableNameHandler actHandler = (AutoCreatedTableNameHandler) handler;
                    actHandler.setAutoCreateTable(properties.isAutoCreateTable());
                }

                return handler.dynamicTableName(sql, tableName);
            }
        }
        return tableName;
    }
}
